import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    TouchableOpacity,

} from 'react-native';

export default class ButtonComponent extends Component {
    constructor(props) {
        super(props);
        this.state = {
            timerCount: this.props.timerCount,
            timerTitle: this.props.timerTitle ||'获取验证码',
            counting: false,
            selfEnable: true,
            textColor: this.props.textColor,
            borderColor:this.props.borderColor||{borderColor:'#6590ff'}
        };
    }
    countDownAction=()=>{
        const codeTime = this.state.timerCount;
        this.interval = setInterval(() =>{
            const timer = this.state.timerCount - 1;
            if(timer===0){
                this.interval&&clearInterval(this.interval);
                this.setState({
                    timerCount: codeTime,
                    timerTitle: this.props.timerTitle || '获取验证码',
                    counting: false,
                    selfEnable: true
                })
            }else{
                this.setState({
                    timerCount: timer,
                    timerTitle: `${timer}s`,
                })
            }
        },1000)
    }
    shouldStartCountting=(shouldStart)=>{
        if (shouldStart) {
            this.countDownAction();
            this.setState({counting: true,selfEnable:false})
        }else{
            this.setState({selfEnable:true})
        }
    }
    componentWillUnmount(){
        clearInterval(this.interval)
    }
    render() {
        const {onClick} = this.props;
        const {counting,timerTitle,selfEnable,textColor,borderColor} = this.state;
        return (
            <TouchableOpacity
                activeOpacity={counting ? 1 : 0.5}
                onPress={()=>{
                    if (!counting &&selfEnable) {
                        this.setState({
                            selfEnable:false});
                        onClick(this.shouldStartCountting)
                    }
                }}>
                <View style={[borderColor,{
                    width:60,
                    height:19,
                    alignItems:'center',
                    justifyContent:'center',
                    borderWidth:0.5,
                    borderRadius:5,
                }]}>
                    <Text style={[textColor,{fontSize:9,backgroundColor:'rgba(0,0,0,0)'}]}>
                        {timerTitle}</Text>
                </View>
            </TouchableOpacity>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
});
